package org.zhc.util;

import java.lang.reflect.Type;

import org.apache.log4j.Logger;

public class TypeConvertUtil {

	private static final Logger logger = Logger.getLogger(TypeConvertUtil.class
			.getName());

	/**
	 * 数据类型转换，需要说明的是，如果没有值，那么该方法会返回其对应的一个默认值，并不会返回null；还有就是如果没有找到
	 * 这个方法所能转换的类，才会返回null
	 * 
	 * @param value
	 *            字符串型的值
	 * @param type
	 *            变量类型
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T convert(String value, Class<T> type) {
		if (type != null) {
			try {
				if (type.equals(Integer.class) || type.equals(int.class)) {
					if (value == null) {
						value = "0";
					}
					return (T) Integer.valueOf(value);
				} else if (type.equals(String.class)) {
					if (value == null) {
						value = "";
					}
					return (T) value;
				} else if (type.equals(Float.class) || type.equals(float.class)) {
					if (value == null) {
						value = "0";
					}
					return (T) Float.valueOf(value);
				} else if (type.equals(Double.class)
						|| type.equals(double.class)) {
					if (value == null) {
						value = "0";
					}
					return (T) Double.valueOf(value);
				} else if (type.equals(Short.class) || type.equals(short.class)) {
					if (value == null) {
						value = "0";
					}
					return (T) Short.valueOf(value);
				} else if (type.equals(Boolean.class)
						|| type.equals(boolean.class)) {
					if (value == null) {
						value = "true";
					}
					return (T) Boolean.valueOf(value);
				} else if (type.equals(Long.class) || type.equals(long.class)) {
					if (value == null) {
						value = "0";
					}
					return (T) Long.valueOf(value);
				} else if (type.equals(Character.class)
						|| type.equals(char.class)) {
					if (value == null) {
						value = " ";
					}
					return (T) Character.valueOf(value.charAt(0));
				} else if (type.equals(java.sql.Date.class)) {
					if (value == null) {
						value = "1970-01-01";
					}
					return (T) java.sql.Date.valueOf(value);
				} else if (type.equals(java.sql.Time.class)) {
					if (value == null) {
						value = "00:00:00";
					}
					return (T) java.sql.Time.valueOf(value);
				} else if (type.equals(java.sql.Timestamp.class)) {
					if (value == null) {
						value = "1970-01-01 00:00:00";
					}
					return (T) java.sql.Timestamp.valueOf(value);
				} else if (type.equals(java.util.Date.class)) {
					if (value == null) {
						value = "1970-01-01";
					}
					return (T) new java.text.SimpleDateFormat().parse(value);
				} else {
					logger.error("Warning:There has no suitable type to convert.");
					return null;
				}
			} catch (Exception e) {
				logger.error("Warning:Parameters type convert error."
						+ e.getMessage());
			}
		}
		return null;
	}

}
